﻿using System.IO;
using System.Linq;
using UnityEditor;


namespace RStudio.UIFramwork.Editor
{
    /// <summary>
    /// Unity 集成文件夹处理
    /// </summary>
    public class UnitFileUtil
    {
        /// <summary>
        /// 创建文件目录
        /// </summary>
        /// <param name="folderPath"></param>
        public static void CreateFolder(string folderPath)
        {
            string[] folders = folderPath.Split('/');
            string path = folders[0];

            for (int i = 1; i < folders.Length; i++)
            {
                path = $"{path}/{folders[i]}";

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
#if UNITY_EDITOR
            AssetDatabase.Refresh();
#endif
        }


        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T GetFile<T>(string fileName) where T : UnityEngine.Object
        {
#if UNITY_EDITOR
            string[] assets = UnityEditor.AssetDatabase.FindAssets(fileName);
            if (assets.Length == 0)
            {
                UnityEngine.Debug.LogError("资源引用失败");
                return default;
            }

            string path = AssetDatabase.GUIDToAssetPath(assets[0]);

            UnityEngine.Debug.Log($"获取文件|路径：{path}");

            return AssetDatabase.LoadAssetAtPath<T>(path);            
#endif
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetPath(string fileName)
        {
            string[] assets = AssetDatabase.FindAssets(fileName);

            if (assets.Length == 0) return null;

            if (assets.Length == 1) return AssetDatabase.GUIDToAssetPath(assets[0]);
     
            assets = assets.Select(x => AssetDatabase.GUIDToAssetPath(x)).ToArray();
            return assets.ToList().Find(e => Path.GetFileNameWithoutExtension(e) == fileName);
        }


        /// <summary>
        /// 写入 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="content"></param>
        public static void Save(string filePath, string content)
        {
            using StreamWriter sw = new(filePath, false);
            {
                sw.Write(content);
                sw.Close();
                sw.Dispose();
            }

#if UNITY_EDITOR
            AssetDatabase.Refresh();
#endif
        }
    }
}
